package json

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
)

type PersonJson struct {
	Name, Email string
	Age         int
}

// 结构体 ——> json
func Marshal() {
	p := PersonJson{"tom", "tom@gmail.com", 30}
	b, _ := json.Marshal(p)
	fmt.Printf("b: %v\n", string(b))
}

func Marshal2() {
	type Person struct {
		Name   string
		Age    int
		Email  string
		Parent []string
	}

	p := Person{
		Name:   "tom",
		Age:    20,
		Email:  "tom@gmail.com",
		Parent: []string{"big tom", "big kite"},
	}

	b, _ := json.Marshal(p)
	fmt.Printf("b: %v\n", string(b))
}

func Marshal3() {
	f, _ := os.Open("a.json")
	dec := json.NewDecoder(f)
	enc := json.NewEncoder(os.Stdout)
	for {
		var v map[string]interface{}
		if err := dec.Decode(&v); err != nil {
			log.Println(err)
			return
		}
		fmt.Printf("v: %v\n", v)
		if err := enc.Encode(&v); err != nil {
			log.Println(err)
			return
		}

	}
}

func Marshal4() {
	f, _ := os.Open("a.json")
	defer f.Close()
	dec := json.NewDecoder(f)
	var v map[string]interface{}
	dec.Decode(&v)
	fmt.Printf("v: %v\n", v)

}

func Marshal5() {
	type Person struct {
		Name   string
		Age    int
		Email  string
		Parent []string
	}

	p := Person{
		Name:   "tom",
		Age:    20,
		Email:  "tom@gmail.com",
		Parent: []string{"big tom", "big kite"},
	}

	f, _ := os.OpenFile("a.json", os.O_WRONLY, 0777)
	defer f.Close()
	enc := json.NewEncoder(f)
	enc.Encode(p)

}

// json -> 结构体
func Unmarshal() {
	b := []byte(`{"Name":"tom","Email":"tom@gmail.com","Age":30}`)
	var m PersonJson
	json.Unmarshal(b, &m)
	fmt.Printf("m: %v\n", m)
}

// 嵌套类型
func UnmarshalUnknown() {
	b := []byte(`{"Name":"tom","Email":"tom@gmail.com","Age":30, "Parents":["tom","Bob"]}`)
	// var m interface{}
	var m map[string]interface{}
	json.Unmarshal(b, &m)
	fmt.Printf("m: %v\n", m)

	for k, v := range m {
		fmt.Printf("k: %v - v: %v \n", k, v)
	}

}
